var contextPath = $("#contextPath").val();
$(function() {
	var shoppingcart_list = $("#shoppingcart_list");
	var shoppingcart_bar = $("#shoppingcart_bar");
	var allSelect,ratioConfigure;
	var load = layer.open({type: 2,shadeClose:false});
	dataInit();
	function dataInit(){
		
		$.ajax({
			url:contextPath+"/shoppingCart/getList.do",
			type:"post",
			async:true,
			dataType:"json",
			success : function(data, textStatus) {
				var state = data.result.state;
				var goodsList = data.goodsList;
				if(state == 1 && goodsList.length >0){
					var html ='';
					$.each(goodsList,function(i,v){
						var price = (v.isSales == '01')?v.realPrice:v.price;
						var bidPrice = v.bidPrice;
						var marketPrice = v.marketPrice;
						var changePoints = v.changePoints;
						var changePrice = v.changePrice;
						var changeShowPoints = v.changePoints;
						if(v.isSelectSpec == "01"){
							ratioConfigure = data.ratioConfigure;
							changePoints = getReqPoints(bidPrice,marketPrice,price);
							changeShowPoints = getShowReqPoints(bidPrice,marketPrice,price);
							changePrice = toDecimal(price-changePoints);
						}
						var pointsView,isPointsSelect;
						 if(v.isPointsBuy =='00'){
							 pointsView = '<p class="normal">&yen;'+price+'</p>',isPointsSelect="";
							 if(v.returnPoints>0){
								 pointsView+='<p class="commodity__live_voucher">赠 <em class="n">'+v.returnPoints+'</em>兑换券</p>';
							 }
							}else{
								price = changeShowPoints + changePrice;
								$(".normal").hide();
								if(v.changePrice == 0){
									pointsView = '<p class="rebate"><em class="n">'+changeShowPoints+'</em> 兑换券</p>';
								}else{
									pointsView = '<p class="rebate"><em class="n">'+changeShowPoints+'</em> 兑换券</p><p class="rebate"> + <span>'+changePrice+'</span>元</p>';
								}
								
								isPointsSelect ='<i class="vip_mark"></i>';
							}
						html += '<li class="shoppingcart__item"><div class="goods_select"><a class="simulation_checkbox simulation_checkbox_active" goodsId="'+v.id+'" spec="'+v.spec+'"  price="'+price+'" href="javascript:;"></a></div><div class="goods_img">'+isPointsSelect+'<a href="'+ contextPath +'/goods/detailPage?goodsId=' + v.id + '"><img src="'+v.thumb+'"></a></div><div class="goods_info"><h4 class="goods_info_name"><a href="'+ contextPath +'/goods/detailPage?goodsId=' + v.id + '">'+v.title+'</a><div class="goods_info_price tr">'+pointsView+'</div></h4>';
						var goodsSpecPro = v.params.goodsSpecPro;
						if(goodsSpecPro != null && goodsSpecPro.length > 0){
							$.each(goodsSpecPro,function(specI,specV){
								html+='<p class="goods_info_color">'+specV.labelName+'：'+specV.attrName+'</p>';
							});
							
						}
						
						html +=	'<p class="goods_info_operate tj"><span class="quantity dib vm"><a class="quantity_subtract dib vm" href="javascript:;">-</a><input class="quantity_input dib vm" type="number" value="'+v.buyNum+'" min="0" name="buyNum"><a class="quantity_add dib vm" href="javascript:;">+</a></span><span class="btn_del dib vm" gid="'+v.id+'" spec="'+v.spec+'" buynum="'+v.buyNum+'"></span></p></div></li>';	
					});
					html+='<form id="shopCartForm" method="post"><input type="hidden" name="goodsId" id="goodsId" value=""></form>';
					shoppingcart_list.append(html);
					//初始化组件
					subInit();
					shoppingcart_list.show();
					shoppingcart_bar.show();
					
				}else{
					$("#shoppingcart_empty").css({'display':'flex'});
				}
				setTimeout(function(){layer.close(load);},50);
				
			},
			error : function(XMLHttpRequest, textStatus, errorThrown){
				setTimeout(function(){layer.close(load);},50);
				layer.open({
				    content:textStatus,
				    time: 2
				});
			}
		});	
		
	}

$(document).on('click','.btn_del', function() {
	var $this = $(this);
	layer.open({
	      title: '提示',
	      content: '确认删除吗？',
	      btn: ['确认','取消'],
	      className: 'dizhi-layer',
	      yes: function(index) {
	    	  deleteShopCart($this);
	      },
	      no: function(index) {
	        layer.close(index);
	      }
	     });
	
});

function deleteShopCart(obj){
	$.ajax({
			url:contextPath+"/shoppingCart/delShopCartOne",
			type:"post",
			async:true,
			data:{goodsId:obj.attr('gid'),spec:obj.attr('spec'),buyNum:obj.attr('buynum')},
			dataType:"json",
			success : function(data, textStatus) {
			var state = data.result.state;
			if(state == null){
				layer.open({
				    content: '删除失败！',
				    style: 'background-color:rgba(0,0,0,.8); color:#fff; border:none;',
				    time: 1,
				    shade: false
				    
				});	
			}else{
				var message = data.result.message;
				layer.open({
				    content: message,
				    style: 'background-color:rgba(0,0,0,.8); color:#fff; border:none;',
				    time: 1,
				    shade: false 
				});	
				if(state == 1){
					obj.parents('li').remove();
					showInit();
				}
			}
			}
		});
}

function checkInit(){
	
	form.Checkbox('.goods_select', {
	    onchange: function(Checkbox, _this) {
	      var is = Checkbox.iSelect,
	        ele = Checkbox.ele,
	        payment = document.querySelector('.payment_info em');
	      if (_this.id === 'iSelect') {
	        if (!is) {
	          [].forEach.call(ele, function(ele) {
	            ele.querySelector('.simulation_checkbox').classList.remove('simulation_checkbox_active');
	            // payment.innerHTML = '&yen;0';
	          });
	        } else {
	          [].forEach.call(ele, function(ele) {
	            ele.querySelector('.simulation_checkbox').classList.add('simulation_checkbox_active');
	          });
	        }

	      }
	      sumFn();
	    }
	  })
}


function sumFn() {
	var selectActive = $('.shoppingcart__item .simulation_checkbox_active');
	var payment = $('#shoppingcart_bar');
	var sum = 0,goodsNum=selectActive.length;
	
	$.each(selectActive,function(i,v){
		var price = $(v).attr('price');
		var num = $(v).closest('li').find('input[name=buyNum]').val();
		sum +=price * num;
	});
	
    
    payment.find('.payment_info em').html('&yen;' + toDecimal(sum));
    payment.find('.payment_submit #allNum').html(goodsNum);
  };
  
  function toDecimal(x) {    
	    var f = parseFloat(x);    
	    if (isNaN(f)) {    
	        return;    
	    }    
	    f = Math.round(x*100)/100;    
	    return f;    
	} 
function subInit(){
	var allSelect = $('.simulation_checkbox');
	var time;
	  new Compute({
		    oninit: function(compute) {
		      sumFn();
		    },
		    onclick: function(compute, _this) {
		    	var index = compute.index,
			    	buyNum = compute.input[index].value;
		    	var oneSelect = allSelect.eq(index);
		    	showInit();
		    	clearTimeout(time);
		    	if(!!buyNum){
		    	time = setTimeout(function(){
		    		updateBuyNum(oneSelect.attr('goodsId'),buyNum,oneSelect.attr('spec'));
		    	},500);
		    	}
		      sumFn();
		    }
		  });
	  checkInit(); 
}  

function showInit(){
	var buyNums = $("input[name=buyNum]");
	var value = 0;
	$.each(buyNums,function(i,v){
		value +=parseInt($(v).val());
	});
	$("#shopCartFloat").find('em').html(value);
	if(value > 0){
	$("#shopCartFloat").find('em').show();
	}else{
		$("#shopCartFloat").find('em').hide();	
	}
	sumFn();
	if($(".shoppingcart__item").length==0){
		shoppingcart_list.hide();
		shoppingcart_bar.hide();
		$("#shoppingcart_empty").css({'display':'flex'});
	}
	
}

//更新购物车购买数量
function updateBuyNum(goodsId,buyNum,spec){
	
	$.ajax({
		url:contextPath+"/shoppingCart/updateBuyNum",
		type:"post",
		async:true,
		data:{goodsId:goodsId,buyNum:buyNum,spec:spec},
		dataType:"json",
		success : function(data, textStatus) {}
	});
	
}


$(".btn_submit").on("click",function(){
	var selectShopCart = $("#shoppingcart_list .simulation_checkbox_active");
	if(selectShopCart.length == 0){
		layer.open({
		    title: '提示',
		    content: '您未选择商品',
		    btn: ['我知道了']
		});	
		return;
	}
	var goodsArray=new Array();  
	selectShopCart.each(function(){
		goodsArray.push($(this).attr('goodsId'));
	});
	$("#goodsId").val(goodsArray.join(','));
	if($("#goodsId").val()==''){
		layer.open({
		    title: '提示',
		    content: '您未选择商品',
		    btn: ['我知道了']
		});	
		return;
	}

	$("#shopCartForm").attr("action",contextPath+"/pay/confirm_shopCart").submit();
});
function getReqPoints(bidPrice, marketPrice, price){
	var changePoints = 0;
	var discount = toDecimal3(bidPrice/marketPrice);
	var minRatio = ratioConfigure.minRatio;
	var maxRatio = ratioConfigure.maxRatio;
	if(discount<=minRatio){
		changePoints = price;
	}else if(discount<=maxRatio){
		changePoints = parseInt(price*(1-discount/10)/(1-minRatio/10));
	}
	return changePoints;
}

function getShowReqPoints(bidPrice, marketPrice, price){
	var changePoints = 0;
	var discount = toDecimal3(bidPrice/marketPrice);
	var minRatio = ratioConfigure.minRatio;
	var maxRatio = ratioConfigure.maxRatio;
	if(discount<=minRatio){
		changePoints = Math.ceil(price);
	}else if(discount<=maxRatio){
		changePoints = parseInt(price*(1-discount/10)/(1-minRatio/10));
	}
	return changePoints;
}

function toDecimal3(x) {    
    var f = parseFloat(x);    
    if (isNaN(f)) {    
        return;    
    }    
    f = Math.round(x*1000)/100;    
    return f;    
} 

});